<%-- 
    Document   : jspModel
    Created on : Feb 29, 2012, 4:11:44 AM
    Author     : 章哲原
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <title>用户管理</title>
        <%--<%@include file="/WEB-INF/jspf/top_easyui.jspf" %>--%>
        <%@include file="/WEB-INF/jspf/top_easyui.jspf" %>
        <script>
            //快捷搜索方法
            function doSearch(value, name) {
                var params = {};
                params[name] = value;
                $('#list_user').datagrid('load', params);
            }
            //角色搜索searchBox
            function doRoleSearch(value, name) {
                var params = $('#list_role').datagrid('options').queryParams; //先取得 datagrid 的查询参数  
                params[name] = value; //设置查询参数  
                $('#list_role').datagrid('load');
            }
            //添加对话框控件启用/禁用
            function widgetStatus(action) {
                $("#add_user_form").find(".easyui-textbox,.easyui-combobox,.easyui-combotree").textbox(action);
            }

            function modify(id) {
                $.ajax({
                    url: "${contextPath}/user/modify/ui.json",
                    success: function (data) {
                        $("#update_user_bt").show();
                        $("#add_user_bt").hide();
                        $('#dept_Id').combotree({data: data.DEPTLIST_JSON});
                        //账号不能修改
                        $("#uNo").textbox('disable');
                        var selected = $('#list_user').datagrid('getSelected');
                        if (selected) {
                            $.ajax({
                                type: "post",
                                url: "${contextPath}/user/modify/role.json?userId=" + selected.id,
                                success: function (details) {
                                    $('#list_role').datagrid('load');
                                    $('#list_role').datagrid('clearSelections');
                                    //回填数据
                                    $.each(details.roleId, function (i, v) {
                                        $('#list_role').datagrid('selectRecord', v);
                                    });

                                    $('#add_user_form').form('load', selected);
                                    $("#add_dialog").dialog("hcenter");
                                    $("#add_dialog").dialog("open");
                                }
                            });
                        }
                    }
                })
            }
            function showDetail(id) {
                $.ajax({
                    url: "${contextPath}/user/detail/ui.json",
                    success: function (data) {
                        //加载部门树
                        $('#dept_Id').combotree({data: data.DEPTLIST_JSON});
                        //禁用编辑按钮
                        $("#add_user_bt,#update_user_bt").hide();
                        var selected = $('#list_user').datagrid('getSelected');
                        if (selected) {
                            $.ajax({
                                type: "post",
                                url: "${contextPath}/user/detail/user.json?userId=" + selected.id,
                                success: function (details) {
                                    $('#list_role').datagrid('load');
                                    $('#list_role').datagrid('clearSelections');
                                    //回填数据
                                    $.each(details.roleId, function (i, v) {
                                        $('#list_role').datagrid('selectRecord', v);
                                    });
                                    //禁用控件
//                                    widgetStatus("disable");
                                    $('#add_user_form').form('load', selected);
                                    $("#add_dialog").dialog("hcenter");
                                    $("#add_dialog").dialog("open");
                                }
                            });
                        }
                    }
                });
            }
            function del(id) {
                var selected = $('#list_user').datagrid('getSelected');
                if (selected) {
                    $.messager.confirm('友情提示', '你确定要删除用户账户为<span id="rp_user_name"  style="color: #0066cc;padding: 0 3px" >' + selected.name + '</span>的用户吗？',
                            function (r) {
                                if (r) {
                                    $.ajax({
                                        type: "post",
                                        url: "${contextPath}/user/delete.json?userId=" + selected.id,
                                        success: function () {
                                            $.messager.alert("友情提示", "删除成功！", 'info');
                                            $('#list_user').datagrid('reload');
                                        }
                                    });
                                }
                            });
                } else {
                    $.messager.alert('友情提示', '请选中一个用户进行操作', 'warning');
                }
            }
            function toLock(id) {
                var selected = $('#list_user').datagrid('getSelected');
                if (selected) {
                    if (selected.status == '0') {
                        //confirm(title,内容,当点击ok后的动作)
                        $.messager.confirm('友情提示', '你确定要冻结用户账户为<span id="rp_user_name"  style="color: #0066cc;padding: 0 3px" >' + selected.name + '</span> 的用户吗？',
                                function (r) {
                                    if (r) {
                                        $.ajax({
                                            type: "post",
                                            url: "${contextPath}/user/modify/lockUser.json?userId=" + id + "&action=lock",
                                            success: function () {
                                                $('#list_user').datagrid('reload');
                                            }
                                        });
                                    }
                                });
                    } else {
                        //confirm(title,内容,当点击ok后的动作)
                        $.messager.confirm('友情提示', '你确定要激活用户账户为 <span id="rp_user_name"  style="color: #0066cc;padding: 0 3px" >' + selected.name + '</span> 的用户吗？', function (r) {
                            if (r) {
                                $.ajax({
                                    type: "post",
                                    url: "${contextPath}/user/modify/lockUser.json?userId=" + id + "&action=unlock",
                                    success: function () {
                                        $('#list_user').datagrid('reload');
                                    }
                                });
                            }
                        });
                    }
                } else {
                    $.messager.alert('友情提示', '请选中一个用户进行操作', 'warning');
                }
            }
            function resetPwd(id) {
                var selected = $('#list_user').datagrid('getSelected');
                if (selected) {
                    $.messager.confirm('友情提示', '你确定要为用户账户为<span id="reset_user_name"  style="color: #0066cc;padding: 0 3px" >' + selected.name + '</span>重置密码吗？',
                            function (r) {
                                if (r) {
                                    $.ajax({
                                        type: "post",
                                        url: "${contextPath}/user/resetpwd.json?userId=" + selected.id,
                                        success: function () {
                                            $.messager.alert('友情提示', "重置密码成功", 'info');
                                        }
                                    });
                                }
                            });
                } else {
                    $.messager.alert('友情提示', '请选中一个用户进行操作', 'warning');
                }
            }

            $(function () {
                //保存的表格
                $('#list_user').datagrid({
                    singleSelect: true, fit: true, fitColumns: false, striped: true,
                    pagination: true, border: false, rownumbers: true,
                    idField: 'id', url: "${contextPath}/user/list/data.json",
                    frozenColumns: [[
                            {field: 'oper', title: '操作', width: 150, align: 'center',
                                formatter: function (value, row, index) {
                                    var operContent = '';
            <shiro:hasPermission name="user:detail:*">
                                    '<a href="javascript:showDetail(' + row.id + ');" class="tdmenuImg"><img title="详情" src="${contextPath}/resources/css/icons/detail.png"/></a>';
            </shiro:hasPermission>
            <shiro:hasPermission name="user:modify:*">
                                    operContent += '<a href="javascript:modify(' + row.id + ');" class="tdmenuImg"><img title="修改" src="${contextPath}/resources/css/icons/pencil.png"/></a>';
            </shiro:hasPermission>
            <shiro:hasPermission name="user:delete:*">
                                    operContent += '<a href="javascript:del(' + row.id + ');" class="tdmenuImg"><img title="删除" src="${contextPath}/resources/css/icons/delete.png"/></a>';
            </shiro:hasPermission><shiro:hasPermission name="user:modify:*">
                                    if (row.status == '0') {
                                        operContent = operContent + '<a href="javascript:toLock(' + row.id + ');" id="lock' + index + '" class="tdmenuImg"><img title="冻结" src="${contextPath}/resources/css/icons/lock.png"/></a>';
                                    } else {
                                        operContent = operContent + '<a href="javascript:toLock(' + row.id + ');" id="lock' + index + '" class="tdmenuImg"><img title="激活" src="${contextPath}/resources/css/icons/key.png"/></a>';
                                    }
            </shiro:hasPermission>
                                    operContent = operContent + '<a href="javascript:resetPwd(' + row.id + ');" class="tdmenuImg"><img title="重置密码" src="${contextPath}/resources/css/icons/resetkey.png"/></a>';
                                    return operContent;
                                }
                            },
                            {field: 'account', title: '用户账户', width: 100, sortable: true},
                            {field: 'name', title: '姓名', width: 100, sortable: true}
                        ]],
                    columns: [[
                            {field: 'deptName', title: '所属部门', width: 100, sortable: true},
                            {field: 'status', title: '状态', width: 100, sortable: true,
                                formatter: function (value, row, index) {
                                    if (value == '0') {
                                        return "激活";
                                    } else {
                                        return "冻结";
                                    }
                                }
                            }
                        ]]
                });
                $('#btn_new').click(function () {
                    $.ajax({
                        url: "${contextPath}/user/add/ui.json",
                        success: function (data) {
                            //填充部门数据
                            $('#dept_Id').combotree({data: data.DEPTLIST_JSON});
                            $("#uNo").textbox('enable');

                            //切换按钮
                            $("#add_user_bt").show();
                            $("#update_user_bt").hide();

                            //清空表单数据
                            $("#add_user_form").form('clear');
                            //定义下拉框默认值
                            $("#sex").combobox('select', 1);
                            $("#certType").combobox('select', 1);
                            $("#status").combobox('select', 0);
                            //打开后清空角色列表
                            $('#list_role').datagrid('load');
                            $('#list_role').datagrid('clearSelections');

                            $("#add_dialog").dialog("hcenter");
                            $("#add_dialog").dialog("open");
                        }
                    })
                });
                //查询
                function doUserSearch() {
                    var params = $('#list_user').datagrid('options').queryParams; //先取得 datagrid 的查询参数  
                    var fields = $('#query_form').serializeArray(); //自动序列化表单元素为JSON对象  
                    $.each(fields, function (i, field) {
                        params[field.name] = field.value; //设置查询参数 field.name为组件name，field.value为组件值 
                    });
                }
                $("#a_search").click(function () {
                    doUserSearch();
                    $('#list_user').datagrid('load');
                });
                //查询清空
                $("#a_reset").click(function () {
                    $('#query_form').form('clear');
                    doUserSearch();
                    $('#list_user').datagrid('load');
                });
                //添加弹出添加、修改、详细信息的dialog
                $("#add_dialog").dialog({
                    title: "用户信息",
                    iconCls: "icon-person",
                    closed: true,
                    modal: true,
                    maximizable: true,
                    shadow: false,
                    width: 720,
                    top: 20,
                    buttons: [{
                            id: 'add_user_bt',
                            text: '保存',
                            iconCls: 'icon-save',
                            handler: function () {//保存时的动作
                                //清空角色id隐藏表单域
                                $("#add_user_form input[name='roleId']").remove();
                                var rows = $('#list_role').datagrid('getSelections');
                                for (var i = 0; i < rows.length; i++) {
                                    //保存角色
                                    $("#add_user_form").append("<input type='hidden' name='roleId' value='" + rows[i].id + "' />")
                                }
                                var upOptions = {//表单提交前的配置（jquery-form）
                                    url: "${contextPath}/user/add/user.json", //即action地址
                                    type: "POST",
                                    beforeSubmit: function () {
                                        if (rows == "" || rows == null) {
                                            $.messager.alert('系统提示', '请选择角色！', 'warning');
                                            return false;
                                        }
                                        return $("#add_user_form").form('validate'); //返回表单验证是否成功，成功返回true，表单进行提交，失败返回false，表单无法提交
                                    },
                                    //表单提交成功后执行
                                    success: function (addData) {//提交成功后执行的操作，addData（形参，可任意取名）为返回的json，
                                        if (addData.ifAdd) {
                                            $.messager.alert('友情提示', '添加用户成功！', 'info');
                                            $('#add_dialog').dialog('close');
                                            $('#list_user').datagrid('reload');
                                        } else {
                                            $.messager.alert("友情提示", "添加用户失败，请稍后再试！", "error");
                                        }
                                    }
                                };
                                $("#add_user_form").ajaxSubmit(upOptions);//表单进行提交，带上option参数，提交成功后完成option里的动作
                            }
                        }, {
                            id: 'update_user_bt',
                            text: '修改',
                            iconCls: 'icon-fileupdate',
                            handler: function () {//修改时的动作
                                //清空角色id隐藏表单域
                                $("#add_user_form input[name='roleId']").remove();
                                var rows = $('#list_role').datagrid('getSelections');
                                for (var i = 0; i < rows.length; i++) {
                                    $("#add_user_form").append("<input type='hidden' name='roleId' value='" + rows[i].id + "' />")
                                }
                                var upOptions = {
                                    url: "${contextPath}/user/modify/user.json",
                                    type: "POST",
                                    dataType: "json",
                                    beforeSubmit: function () {
                                        if (rows == "" || rows == null) {
                                            $.messager.alert('系统提示', '请选择角色！', 'warning');
                                            return false;
                                        }
                                        return $("#add_user_form").form('validate');
                                    },
                                    //表单提交成功后执行
                                    success: function (updataData) {
                                        if (updataData.ifUpdate) {
                                            $.messager.alert('友情提示', '修改用户成功！', 'info');
                                            $('#list_user').datagrid('reload');
                                            $('#add_dialog').dialog('close');
                                        } else {
                                            $.messager.alert("友情提示", "修改用户失败，请稍后再试！", "error");
                                        }
                                    }
                                };
                                $("#add_user_form").ajaxSubmit(upOptions);
                            }
                        }, {
                            text: '取消',
                            handler: function () {
                                $('#add_dialog').dialog('close');
                            }
                        }]
                });

                /*
                 * easyui远程验证ajax设为同步，而且在每按下一个键时就验证，用户体验很差
                 * 改为失去焦点时验证
                 * 这里的要用textbox()，跟控件类型一致，而不能用validatebox()
                 */
                $("#uNo").textbox({validType: 'custom_remote["${contextPath}/user/list/validUserNo.json","account"]'});
                $("#uNo").textbox('textbox').blur(function () {
                    $("#uNo").textbox('enableValidation');
                }).keydown(function () {
                    $("#uNo").textbox('disableValidation');
                });

                //修改添加时的角色列表
                $('#list_role').datagrid({
                    border: false, fit: true,
                    fitColumns: false, striped: true,
                    url: "${contextPath}/user/list/role.json",
                    idField: 'id', //主键字段  
                    queryParams: {}, //查询条件  
                    pagination: false, //显示分页  
                    rownumbers: true, //显示行号
                    loadMsg: "正在加载，请稍候...", //远程加载时的提示信息
                    frozenColumns: [[
                            {field: 'ck', width: 20, checkbox: true}
                        ]],
                    columns: [[
                            {field: 'name', title: '角色名称', width: 200, sortable: true},
                            {field: 'remark', title: '角色描述', width: 400, sortable: true}
                        ]]
                });

                //角色重新加载
                $("#do_reload").click(function () {
                    //为searchbox重新设置值
                    $("#search_role").searchbox('setValue');
                    //取得searchbox的值
                    var gv = $("#search_role").searchbox('getValue');
                    //取得规则名称
                    var gn = $("#search_role").searchbox('getName');
                    doRoleSearch(gv, gn);
                });
                $("#selected_rows").click(function () {
                    var ids = [];
                    var rows = $('#list_role').datagrid('getSelections');
                    for (var i = 0; i < rows.length; i++) {
                        ids.push(rows[i].name);
                    }
                    $.messager.alert('业务信息', "当前已选的角色：<br/>" + ids.join('、'), 'info');
                });
                // 高级搜索
                function initAdvSearchPanel(height) {
                    if (!height) {
                        height = 44;
                    }
                    $('body').layout('panel', 'north').panel('resize', {height: height});
                    $('body').layout('resize');
                }
                initAdvSearchPanel(44);
                $('#btn_adv_search').click(function () {
                    if ($(this).linkbutton('options').selected) {
                        initAdvSearchPanel(125);
                    } else {
                        initAdvSearchPanel(44);
                    }
                });

                // 注册全局ajax错误处理函数
                $(document).ajaxError(new jQueryAjaxErrorHandler());
            });
        </script>
    </head>
    <body class="easyui-layout">
        <script type="text/javascript">
            $("body").mask({
                maskMsg: '<div class="loading_text"><img src="${contextPath}/resources/images/loading_2.gif"/><span>正在初始化，请稍后...</span></div>',
                opacity: 1
            });
            $(function () {
                $("body").mask('hide');
            })
        </script>
        <div region="north" data-options="border:false">
            <div class="easyui-layout" id="menuSearchPanel" data-options="fit:true">
                <div region="north" title="" border="false" id="menubar" style="height:44px;border-bottom-width:1px">
                    <div style="padding:6px;float:left">
                        <input class="easyui-searchbox" data-options="searcher:doSearch,prompt:'请输入快速搜索条件',menu:'#quick_search_menu'"  style="width: 250px"/>
                        <div id="quick_search_menu">
                            <div data-options="name:'account'" id="search_account">用户账户</div>
                            <div data-options="name:'name'" id="search_name">姓名</div>
                        </div>
                    </div>
                    <div style="padding:6px;float:left">
                        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-filter',toggle:true" id="btn_adv_search">高级搜索</a>
                    </div>
                    <shiro:hasPermission name="user:add:*">
                        <div class="datagrid-btn-separator" style="margin-top:8px"></div>
                        <div style="padding:6px;float:left">
                            <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-add'" id="btn_new">新增</a>
                        </div>
                    </shiro:hasPermission>
                </div>
                <!--高级搜索栏-->
                <div id="search_bar" region="center" data-options="border:false" style="border-bottom-width:1px">
                    <form id="query_form" method="post">
                        <div style="padding: 6px;width:800px;margin:0 auto">
                            <input class="easyui-textbox" name="account" data-options="label:'用户账户：',labelAlign:'right',width:250"/>
                            <input class="easyui-textbox"name="name" data-options="label:'姓名：',labelAlign:'right',width:250"/>
                            <select name="status" class="easyui-combobox" data-options="label:'状态：',labelAlign:'right',width:250,panelHeight:100">
                                <option value="">不限</option>
                                <option value="0">激活</option>
                                <option value="1">冻结</option>
                            </select>
                        </div>
                        <div style="padding-bottom:6px;width:200px;margin:0 auto">
                            <a href="Javascript:void(0)" id="a_search" class="easyui-linkbutton" iconCls="icon-search">查 询</a>
                            <span style="padding-left: 50px"></span>
                            <a href="Javascript:void(0)" id="a_reset" class="easyui-linkbutton" iconCls="icon-undo">清 空</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div id="main_container" region="center" data-options="border:false"  title="" style="padding:0px;"> 
            <!--        用户表格-->
            <table  id="list_user" > 
            </table>
        </div>

        <!-- 添加用户对话框 -->
        <div id="add_dialog" class="easyui-dialog" >
            <form method="POST" id="add_user_form" >
                <input name='id' type='hidden' />
                <div id="add_panel" style="padding: 10px; border-bottom-width: 1px;" class="easyui-panel" data-options="title:'基础信息',iconCls: 'icon-form',border:false">
                    <div style="margin-bottom:8px">
                        <input class="easyui-textbox" name="account" id="uNo" data-options="width:220,label:'用户账户：',labelAlign:'right',required:true"/>
                        <input class="easyui-textbox" name="name" id="uName" data-options="width:220,label:'姓名：',labelAlign:'right',required:true"/>
                        <select id="sex" name="sex" class="easyui-combobox" data-options="width:220,label:'性别：',labelAlign:'right',panelHeight:65,editable:false">
                            <option value="1" selected="">男</option>
                            <option value="2">女</option>
                        </select>
                    </div>
                    <div style="margin-bottom:8px">
                        <select id="certType" name="certType" class="easyui-combobox" data-options="width:220,label:'证件类型：',labelAlign:'right',editable:false,panelHeight:92">
                            <option value="1" selected="">身份证</option>
                            <option value="2">军官证</option>
                            <option value="3">护照</option>
                            <option value="4">其他</option>
                        </select>
                        <input class="easyui-textbox" name="certNo" data-options="width:220,label:'证件号码：',labelAlign:'right'"/>
                        <input class="easyui-textbox" name="email" data-options="width:220,label:'电子邮箱：',labelAlign:'right',validType:'email'"/>
                    </div>
                    <div>
                        <input class="easyui-textbox" name="tel" data-options="width:220,label:'固定电话：',labelAlign:'right'"/>
                        <input class="easyui-textbox" name="mobile" data-options="width:220,label:'移动电话：',labelAlign:'right'"/>
                        <select id="status" name="status" class="easyui-combobox" data-options="width:220,label:'状态：',labelAlign:'right',editable:false,panelHeight:65">
                            <option value="0" selected="selected">激活</option>
                            <option value="1">冻结</option>
                        </select>
                    </div>
                </div>
                <!--所属部门信息 -->
                <div id="dept_panel" style="padding:10px; border-bottom-width: 1px;" class="easyui-panel" data-options="title:'基础信息',iconCls: 'icon-form',border:false">
                    <select id="dept_Id" name="deptId" class="easyui-combotree" data-options="width:300,label:'所属部门：',labelAlign:'right',editable:false,required:true"></select>
                </div>
            </form>

            <!-- 角色菜单 -->
            <div id="role_div" class="easyui-panel" data-options="title:'角色列表',iconCls: 'icon-form',border:false,height:250">
                <table toolbar="#role_search_bar" id="list_role"> 
                </table>
            </div>
            <!-- 角色菜单的搜索栏 -->
            <div id="role_search_bar" style="padding: 5px">
                <input id="search_role" class="easyui-searchbox" data-options="menu:'#rn',width:220,prompt:'请输入关键字',searcher:doRoleSearch"/>
                <a href="Javascript:void(0)" id="selected_rows" class="easyui-linkbutton" iconCls="icon-chart" plain="true">查看所选角色</a>
                <a href="Javascript:void(0)" id="do_reload" class="easyui-linkbutton" iconCls="icon-reload" plain="true">重新加载</a>
                <div id="rn" style="width:120px">
                    <div name="name">角色名称</div> 
                </div> 
            </div>
        </div>

    </body>
</html>
